class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        
        vector<vector<string>> result;
        int n = strs.size();
        if(n == 0) return result;

        unordered_map<string, vector<string>>word_map;
        for(int i = 0; i < n; i++){
            string str = strs[i];
            sort(str.begin(), str.end());
            word_map[str].push_back(strs[i]);
        }

        for(auto it = word_map.begin(); it != word_map.end(); it++){
            result.push_back(it->second);
        }

        return result;
    }
};

class Solution {
public:

    bool anagrams_judge(string& str, vector<int> char_map){
        for(int j = 0; j <str.size(); j++){
                char_map[str[j]-'a']--;
        }
        for(int i = 0; i < char_map.size(); i++){
            if(char_map[i] != 0){
                return false;
            }
        }
        return true;
    }

    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        
        vector<vector<string>> result;
        int n = strs.size();
        if(n == 0) return result;

        vector<string> anagrams;
        vector<int> map(n, 0);
        vector<int> char_map(26, 0);

        for(int i = 0; i < n; i++){
            
            if(map[i] != 0) continue;
            
            anagrams.push_back(strs[i]);
            map[i] = 1;
            
            for(int j = 0; j <strs[i].size(); j++){
                char_map[strs[i][j]-'a']++;
            }

            for(int k = i+1; k < n; k++){
                if(anagrams_judge(strs[k], char_map)){
                    anagrams.push_back(strs[k]);
                    map[k] = 1;
                }
            }
            result.push_back(anagrams);

            char_map.clear();
            char_map.resize(26);
            anagrams.clear();
        }

        return result;
    }
};